package com.tywj.navigation.course

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.tywj.panda.customer.common.provider.INavigationService
import com.tywj.panda.customer.common.view.base.MyBaseActivity
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.navigation.R
import com.tywj.navigation.map.NavigationSelectedAddress
import com.tywj.navigation.route.NavigationRoute
import kotlinx.android.synthetic.main.navigation_activity_apply_course.*

/**
 * @desc 申请线路
 * @author June Yang
 * @date 2020/5/13
 */

@Route(path = NavigationRoute.NAVIGATION_APPLY_COURSE)
class NavigationApplyCourseActivity : MyBaseActivity() {

    companion object {
        // 出发地
        private const val REQUEST_START = 1001

        // 目的地
        private const val REQUEST_END = 1002
    }

    // 起点poi
    private lateinit var startPoi: PoiItem

    // 终点poi
    private lateinit var endPoi: PoiItem

    // 是否是第一次获取定位
    private var isFirstLocation = false

    //是否是出发地
    private var isStartPoint = true

    // 预约时间选择器
    private lateinit var appointmentTimePickerView: OptionsPickerView<String>

    // 预约时间数据
    private val hoursList = ArrayList<String>()

    private val minutesList = ArrayList<String>()

    override fun getLayoutID(): Int = R.layout.navigation_activity_apply_course

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)


        // 这里对起点坐标虚构一个poi，方便处理
        startPoi = PoiItem(
            Int.MAX_VALUE.toString(), LatLonPoint(0.0, 0.0),
            ResourcesUtil.getString(R.string.navigation_my_location), ""
        )

        endPoi = PoiItem(
            Int.MAX_VALUE.toString(), LatLonPoint(0.0, 0.0),
            ResourcesUtil.getString(R.string.navigation_my_location), ""
        )

        addTimeList()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        titleLayout.setTitleText(R.string.navigation_apply_course)
        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))

        etPeopleNum.setSelection(etPeopleNum.text.toString().length)

        initAppointmentTimePickerView()
    }

    override fun initListener() {
        super.initListener()

        etStartPoint.onClick {
            NavigationRoute.toSelectAddress(etStartPoint.text.toString(), INavigationService.FROM_START)
                .navigation(this, REQUEST_START)
        }

        etEndPoint.onClick {

            NavigationRoute.toSelectAddress(etEndPoint.text.toString(), INavigationService.FROM_END)
                .navigation(this, REQUEST_END)
        }

        etStartTime.onClick {
            isStartPoint = true
            showAppointmentTimePickerView()
        }
        etReturnTime.onClick {
            isStartPoint = false
            showAppointmentTimePickerView()
        }

        etPeopleNum.onClick {
            shortToast("etPeopleNum")
        }

        btnSubmit.onClick {
            shortToast("submit")
        }

        titleLayout.getRightTextView().onClick {
            NavigationRoute.toApplyHistory().navigation(this)
        }
    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()
        startGetMyCurrentLocation()
    }

    //接收数据
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        //先判断状态
        if (resultCode == Activity.RESULT_OK) {
            val poi: PoiItem = data!!.getParcelableExtra(NavigationSelectedAddress.DATA_POI_ITEM)
            //再判断来自哪个界面
            when (requestCode) {
                REQUEST_START -> updateStartPoint(poi)
                REQUEST_END -> updateEndPoint(poi)
            }
        }
    }

    private fun updateStartPoint(poi: PoiItem) {
        if (poi.poiId == endPoi.poiId) {
            // 起点和终点不能相同
            shortToast(R.string.navigation_start_and_end_are_not_the_same)
            return
        }

        startPoi = poi

        etStartPoint.setText(poi.title)
        etStartPoint.setSelection(poi.title.length)
    }

    private fun updateEndPoint(poi: PoiItem) {

        if (poi.poiId == startPoi.poiId) {
            // 起点和终点不能相同
            shortToast(R.string.navigation_start_and_end_are_not_the_same)
            return
        }
        endPoi = poi

        etEndPoint.setText(poi.title)
        etEndPoint.setSelection(poi.title.length)
    }

    private fun initAppointmentTimePickerView() {
        val timeOptions = OptionsPickerBuilder(this, OnOptionsSelectListener { options1, options2, _, _ ->

            val hour = hoursList[options1]
            val minute = minutesList[options2]

            if (isStartPoint) {
                etStartTime.setText(hour + minute)
            } else {
                etReturnTime.setText(hour + minute)
            }

        }).setTitleText(ResourcesUtil.getString(R.string.navigation_picker_time))
            .setTitleColor(ResourcesUtil.getColor(R.color.common_black_33))
            .setTitleSize(20)
            .setCancelColor(ResourcesUtil.getColor(R.color.common_gray_B2))
            .setSubCalSize(16)
            .setSubmitColor(ResourcesUtil.getColor(R.color.common_yellow_FD))
            .setSubCalSize(16)
            .build<String>()
        timeOptions.setNPicker(hoursList, minutesList, null)
        timeOptions.setSelectOptions(0, 0, 0)
        appointmentTimePickerView = timeOptions

    }

    private fun addTimeList() {
        for (h in 0..23) {
            hoursList.add(String.format(ResourcesUtil.getString(R.string.navigation_hour), h))
        }
        for (m in 0..59) {
            minutesList.add(String.format(ResourcesUtil.getString(R.string.navigation_minute), m))
        }
    }

    private fun showAppointmentTimePickerView() {
        appointmentTimePickerView.show()
    }

    //得到当前位置
    private fun startGetMyCurrentLocation() {
        //获取当前位置
        var mLocationClient: AMapLocationClient? = null
        var mLocationOption: AMapLocationClientOption? = null
        //初始化定位
        mLocationClient = AMapLocationClient(this)
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener)

        mLocationOption = AMapLocationClientOption()
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption.isOnceLocation = true
        mLocationOption.isLocationCacheEnable = false //关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption)

        //启动定位
        mLocationClient.startLocation()
    }

    private var mLocationListener = AMapLocationListener { aMapLocation ->
        aMapLocation?.let {
            //我的位置
            etStartPoint.setText(it.poiName)
        }
    }
}